package org.bhf.validation.annotations;

/**
 * Copyright (c) 2007, Blue Hole Software. All rights reserved.
 * Code licensed under the Apache 2.0 License:
 * http://www.apache.org/licenses/
 */

import org.bhf.i18n.Message;
import org.bhf.i18n.MessageType;
import org.bhf.i18n.Messages;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

/**
 * Test for negative numerical value.
 */
@Documented
@Retention( RetentionPolicy.RUNTIME  )
@Target( ElementType.METHOD )
@Validator
public @interface NonPositive
{
    /**
     * @exclude
     */
    public static final class Validator
    {
        public static boolean validate( final Object value, final String ourKey, final Messages messages, final List<String> stack )
        {
            final NonPositive that = ValidatorRegistry.lookup( ourKey, NonPositive.class );

            try
            {
                if( value != null && Double.parseDouble( value.toString() ) <= 0 )
                    return true;
            }
            catch( NumberFormatException nfe ) { }

            queueMessage( that, messages, stack );
            return false;
        }

        private static void queueMessage( final NonPositive that, final Messages messages, final List<String>stack )
        {
            messages.addMessage(
                new Message(
                    org.bhf.validation.Util.stackToPath( stack ), that.summary(), that.detail(),
                    MessageType.ERROR, that.bundle()
                )
            );
        }
    }

    /**
     * Override the default detail message. Generally, this is a key into a resource bundle.
     * @return The default detail message. Generally, this is a key into a resource bundle.
     */
    public abstract String  detail()    default "errors.nonpositive";

    /**
     * Override the default summary message. Generally, this is a key into a resource bundle.
     * @return The default summary message. Generally, this is a key into a resource bundle.
     */
    public abstract String  summary()   default "errors.nonpositive";

    /**
     * Override the default resource bundle.
     * @return The resource bundle.
     */
    public abstract String  bundle()    default "validation";
}